package net.huashitong.oversee.service;

import com.sirdc.modules.core.dao.BaseDao;
import com.sirdc.modules.sys.base.StringPKService;
import com.sirdc.modules.sys.service.SysTableService;
import com.sirdc.modules.utils.StringUtils;
import net.huashitong.oversee.dao.ScoreSummaryTempDao;
import net.huashitong.oversee.entity.ScoreSummaryTemp;
import net.huashitong.oversee.filter.ScoreSummaryFilter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Collections;
import java.util.Comparator;
import java.util.List;

@Service
public class ScoreSummaryTempService extends StringPKService<ScoreSummaryTemp> {

    @Autowired
    private ScoreSummaryTempDao dao;
    @Autowired
    private SysTableService tableService;

    @Override
    protected BaseDao<ScoreSummaryTemp, String> getDao() {
        return dao;
    }
    @Override
    protected void beforeSave(ScoreSummaryTemp obj) {
        obj.setSysId(tableService.updateMaxSysId("t_scoresummary_temp", null));
    }


    public List<ScoreSummaryTemp> queryByFilterNoPage(ScoreSummaryFilter filter){
        return dao.queryByFilterNoPage(filter);
    }

    public List<ScoreSummaryTemp> queryScoreSummaryByIds(List<String> ids) {
        return dao.queryScoreSummaryByIds(ids);
    }

    public void updateSummaryScoreRank() {
        List<ScoreSummaryTemp> summaries = this.query();
        Collections.sort(summaries, new Comparator<ScoreSummaryTemp>() {
            @Override
            public int compare(ScoreSummaryTemp g1, ScoreSummaryTemp g2) {
                double score1 = Double.parseDouble(StringUtils.isBlank(g1.getScore()) ? "0" : g1.getScore());
                double score2 = Double.parseDouble(StringUtils.isBlank(g2.getScore()) ? "0" : g2.getScore());
                if (score1 < score2) {
                    return 1;
                } else if (score1 == score2) {
                    return 0;
                } else {
                    return -1;
                }
            }
        });
        for (int i = 0, s = summaries.size(); i < s; i++) {
            if (i > 0 && Double.parseDouble(StringUtils.isBlank(summaries.get(i).getScore()) ? "0" : summaries.get(i).getScore())
                    == Double.parseDouble(StringUtils.isBlank(summaries.get(i - 1).getScore()) ? "0" : summaries.get(i - 1).getScore())) {
                summaries.get(i).setRank(summaries.get(i - 1).getRank());
            } else {
                summaries.get(i).setRank(i + 1 + "");
            }
        }
        this.batchUpdate(summaries);
    }

}
